package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

const OneGigaByte int64 = 1024 * 1024 * 1024

func GetFileContentType(output *os.File) (string, error) {
	buf := make([]byte, 512)
	_, err := output.Read(buf)
	if err != nil {
		return "", err
	}

	contentType := http.DetectContentType(buf)
	return contentType, nil
}

func SearchBigDirectory(dir string) {
	var total_capacity float64 = 0.0

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		log.Println(err, "ignored.")
	}

	for _, file := range files {
		if file.IsDir() {
			// fmt.Println(filepath.Join(dir, file.Name()), file.IsDir())
			SearchBigDirectory(filepath.Join(dir, file.Name()))
			continue
		}

		fb, err := os.Open(filepath.Join(dir, file.Name()))

		if err != nil {
			log.Fatal(err)
		}

		defer fb.Close()

		// Get the file content
		contentType, _ := GetFileContentType(fb)

		if strings.Contains(contentType, "text") {
			total_capacity += float64(file.Size())
		}
	}
	if total_capacity > float64(OneGigaByte) {
		GBTotalCapacity := fmt.Sprintf("%.2f", total_capacity/1024/1024/1024)
		fmt.Println(dir, GBTotalCapacity, "GB")
	}

}

func main() {
	if len(os.Args) < 2 {
		log.Fatal("Searching path need specify.")
	}
	if stat, err := os.Stat(os.Args[1]); err == nil && stat.IsDir() {
		// log.Println(os.Args[1], " directory found.")
	} else {
		log.Fatal("Searching path need specify. Not a file.")
	}

	SearchBigDirectory(os.Args[1])
}
